package org.rmc.demo.cfca;

import org.bouncycastle.asn1.DERSet;
import org.bouncycastle.asn1.x509.X509Name;
import org.bouncycastle.jce.PKCS10CertificationRequest;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import sun.misc.BASE64Decoder;

import java.io.InputStream;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.spec.PKCS8EncodedKeySpec;

/**
 * @author ranmc
 * @date 2019/7/19
 */
public class CertUtil {

    public static String content(String name, String identity){
        return "  姓名: " + name + "\n  身份证号: " + identity;
    }

    public static String subject(String name, String identity, String company, String contract){
        String subject = "CN=" + name + "&" + identity;
        subject += ",O=";
        subject += company;
        // 国家：中国
        subject += ",C=CN";
        subject += ",OU=YunSign&";
        subject += contract;
        return subject;
    }

    public static Cert cert(String subject){
        try {
            Security.addProvider(new BouncyCastleProvider());
            X509Name dn = new X509Name(subject);
            KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
            keyGen.initialize(2048);
            KeyPair kp = keyGen.generateKeyPair();
            PKCS10CertificationRequest p10 = new PKCS10CertificationRequest("SHA1WithRSA", dn, kp.getPublic(),
                    new DERSet(), kp.getPrivate());
            byte[] der = p10.getEncoded();
            return new Cert(kp.getPrivate(), new String(cfca.util.Base64.encode(der)));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("生成私钥失败！");
        }
    }

    /**
     * 解密私钥
     * @param key 私钥
     * @return 结果
     */
    public static PrivateKey decrypt(String key){
        try {
            byte[] bytes = new BASE64Decoder().decodeBuffer(key);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return keyFactory.generatePrivate(keySpec);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Certificate certX509(InputStream inputStream) {
        try {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            return cf.generateCertificate(inputStream);
        } catch (CertificateException e) {
            e.printStackTrace();
        }
        return null;
    }

}
